//
//  GDDownloadImageAndCaches.m
//  GraduationDesign
//
//  Created by JiaKang.Zhong on 16/1/6.
//  Copyright © 2016年 JiaKang.Zhong. All rights reserved.
//

#import "GDDownloadImageAndCachesOperation.h"
#import "GDMainViewBGModel.h"


@interface GDDownloadImageAndCaches ()

@property(nonatomic,strong) NSMutableDictionary * imageCaches;
@property(nonatomic,strong) GDDownloadImageAndCaches * downloadImage;

@end
@implementation GDDownloadImageAndCaches


-(NSMutableDictionary *)imageCaches{
    if (!_imageCaches) {
        _imageCaches = [NSMutableDictionary dictionary];
    }
    return _imageCaches;
}

/**
 *  模拟有沙盒内存的缓存
 *
 */
-(void) downloadImageAndCaches:(UIImageView *) imageView  andUrl:(NSString *) imageUrl{
    
//    判断是否已经存在图片，存在那么就直接设置image对象
//     先看内存中是否存在图片

    if ([self.imageCaches objectForKey:imageUrl]) {
        GDLog(@"内存有");
        imageView.image = self.imageCaches[imageUrl];
    }else{
//      在看沙盒中是否存在图片
        UIImage *image = [UIImage imageWithContentsOfFile:[self judgeImageExistCaches:imageUrl]];
        if (image){
            GDLog(@"沙盒有");
            imageView.image = image;
            // 存放到内存中
            [self.imageCaches setObject:image forKey:imageUrl];
        }else{
//            最后没办法了，要下载图片了
            GDLog(@"下载图片");
            NSOperationQueue * queue = [[NSOperationQueue alloc] init];
            [queue addOperationWithBlock:^{
                GDLog(@"%@",[NSThread currentThread]);
                //         下载图片资源
                NSURL * url = [NSURL URLWithString:imageUrl];
                NSData * data = [NSData dataWithContentsOfURL:url];
                UIImage * image = [UIImage imageWithData:data];
                if (image) {
                    // 保存到沙盒中  注意这里是NSDate的形式保存
                    NSString * imgageFile = [self judgeImageExistCaches:imageUrl.lastPathComponent];
                    [data writeToFile:imgageFile atomically:YES];
                    // 写入到内存中
                    [self.imageCaches setObject:image forKey:imageUrl];
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        //            主队列更新UI
                        GDLog(@"%@",[NSThread currentThread]);
                        imageView.image = image;
                    }];
                }
           
            }];
          }
      }
}

#pragma mark 判断文件是否存在于Caches中
-(NSString *) judgeImageExistCaches:(NSString *) imgUrl{
    
    NSString *filepath=[GDCachesFilePath stringByAppendingPathComponent:imgUrl.lastPathComponent];
    return  filepath;
}


-(void)dealloc{
    
    [self.imageCaches removeAllObjects];
}
@end
